package processor;

import model.BaseChange;
import model.BaseProduct;
import model.BaseProductList;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Selectable;
import util.Mytime;

import java.util.ArrayList;
import java.util.List;

//import static processor.LoginProcessor.isRedirectedToLoginPage;

public class ProductProcessor {
    public static void processBasicProduct(Page page){
//3
        BaseProduct baseProduct = new BaseProduct();
        baseProduct.setProduct_unique(page.getUrl().toString()
                                                .replace("https://www.qichacha.com/","")
                                                .replace(".html",""));
        baseProduct.setProduct_name(page.getHtml().xpath("//section//h1/allText()").toString());
        baseProduct.setProduct_url(page.getHtml().xpath("//section[@class='panel panel-default phead n-s b-a']//a[@class='text-primary']/@href").toString());
        String text= page.getHtml().xpath("//section[@class='panel panel-default phead n-s b-a']//small[@class='text-mdclear']/allText()").toString();
        String [] a = text.split(" ");
        if(a.length == 3){
            baseProduct.setFinancing_information(a[0].replace("融资信息：",""));
            baseProduct.setDate(a[1].replace("成立日期：",""));
            baseProduct.setAddress(a[2].replace("所属地：",""));
        }

        baseProduct.setPruduct_info(page.getHtml().xpath("//section[@id='productIntro']//table/tbody/tr/td/allText()").toString());
        baseProduct.setCreatedTime(Mytime.getTime());

        page.putField("BaseProduct",baseProduct);
    }
    public static void processBasicProductList(Page page){
//        if(isRedirectedToLoginPage(page)){
//            return;
//        }
        List<BaseProductList> baseProductLists = new ArrayList<BaseProductList>();
        List<Selectable> nodes = page.getHtml().xpath("//section[@id='productInfo']//table/tbody/tr").nodes();
        if(nodes.size()>1){
            for (int i = 1;i < nodes.size();i++){
                BaseProductList baseProductList = new BaseProductList();
                baseProductList.setProduct_unique(page.getUrl().toString()
                        .replace("https://www.qichacha.com/","")
                        .replace(".html",""));
                baseProductList.setMain_product_name(nodes.get(i).xpath("/tr/td").nodes().get(1).xpath("/td/allText()").toString());
                baseProductList.setMain_product_info(nodes.get(i).xpath("/tr/td").nodes().get(2).xpath("/td/allText()").toString());
                baseProductList.setMain_product_link(nodes.get(i).xpath("/tr/td").nodes().get(3).xpath("/td/a/@href").toString());
                baseProductList.setCreatedTime(Mytime.getTime());
                baseProductLists.add(baseProductList);
            }
        }
        page.putField("BaseProductList",baseProductLists);
    }
}
